using Microsoft.Win32;
using System;

namespace AutoStartManager.Services
{
    /// <summary>
    /// 开机自启动管理器
    /// </summary>
    public class StartupManager
    {
        private const string RegistryKeyPath = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Run";
        private const string AppName = "AutoStartManager";

        /// <summary>
        /// 设置应用程序开机自启动
        /// </summary>
        /// <param name="enabled">是否启用自启动</param>
        /// <param name="executablePath">可执行文件路径</param>
        public void SetAutoStart(bool enabled, string executablePath)
        {
            try
            {
                using var key = Registry.CurrentUser.OpenSubKey(RegistryKeyPath, true);
                if (key == null)
                {
                    throw new Exception("无法访问注册表项");
                }

                if (enabled)
                {
                    key.SetValue(AppName, $"\"{executablePath}\"");
                }
                else
                {
                    key.DeleteValue(AppName, false);
                }
            }
            catch (Exception ex)
            {
                throw new Exception($"设置开机自启动失败: {ex.Message}", ex);
            }
        }

        /// <summary>
        /// 检查应用程序是否设置为开机自启动
        /// </summary>
        /// <param name="executablePath">可执行文件路径</param>
        /// <returns>是否已设置自启动</returns>
        public bool IsAutoStartEnabled(string executablePath)
        {
            try
            {
                using var key = Registry.CurrentUser.OpenSubKey(RegistryKeyPath, false);
                if (key == null)
                {
                    return false;
                }

                var value = key.GetValue(AppName)?.ToString();
                return !string.IsNullOrEmpty(value) && value.Contains(executablePath);
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 获取当前应用程序的可执行文件路径
        /// </summary>
        /// <returns>可执行文件路径</returns>
        public string GetCurrentExecutablePath()
        {
            return System.Reflection.Assembly.GetExecutingAssembly().Location;
        }
    }
}